package com.jdrx.ocp.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.jdrx.logger.bizlogs.BizLoggerService;
import com.jdrx.ocp.beans.commons.SysConstant;
import com.jdrx.ocp.beans.constans.*;
import com.jdrx.ocp.beans.dto.DeleteBaseDTO;
import com.jdrx.ocp.beans.dto.dept.QueryByIdsDTO;
import com.jdrx.ocp.beans.dto.user.*;
import com.jdrx.ocp.beans.entity.DeptPO;
import com.jdrx.ocp.beans.entity.UserPO;
import com.jdrx.ocp.beans.entity.UserRolePO;
import com.jdrx.ocp.beans.entity.util.ExceptionMessageFilter;
import com.jdrx.ocp.beans.event.NoticesEvent;
import com.jdrx.ocp.beans.vo.*;
import com.jdrx.ocp.dao.DeptDAO;
import com.jdrx.ocp.dao.UserDAO;
import com.jdrx.ocp.dao.UserRoleDAO;
import com.jdrx.ocp.dao.UserServiceClickDAO;
import com.jdrx.ocp.utils.Convertor;
import com.jdrx.ocp.utils.LoggerUtil;
import com.jdrx.ocp.utils.ValidateUtils;
import com.jdrx.platform.commons.rest.exception.BizException;
import com.jdrx.platform.jdbc.beans.vo.PageVO;
import com.jdrx.sw.sewage.common.helper.HttpClientHelper;
import com.jdrx.sw.sewage.remote.TenantUserRemote;
import com.jdrx.sw.sewage.service.common.RedisService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author: Huangxg
 * @Date: 2018/11/20 9:46
 */
@Service
public class UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private UserRoleDAO userRoleDAO;
    @Autowired
    private BasicInfoService basicInfoService;
    @Autowired
    private UserServiceClickDAO userServiceClickDAO;
    @Autowired
    private DeptService deptService;
    @Autowired
    private NoticeEventService noticeEventService;
    @Autowired
    private SettingService settingService;
    @Autowired
    private BizLoggerService bizLoggerService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private ValidateUtils validateUtils;
    @Autowired
    private DeptDAO deptDAO;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private TenantUserRemote tenantUserRemote;
    @Value("${aio.flag}")
    private String aioFlag;
    @Value("${tenant.user.add.url}")
    private String tenantUserAddUrl;

    /**
     * 查询黑白名单
     *
     * @param dto
     * @return
     */
    public PageVO<Map<String, Object>> queryUserByStatus(QueryUserWithStatusDTO dto, String tid) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize(), "last_login_time DESC");
        List<Map<String, Object>> userList = userDAO.listByStatus(dto);

        Map<String, Object> map = null;
        //获取是否在线
        for (Map<String, Object> user : userList) {
            map = Maps.newHashMap();
            boolean online = adminService.checkUserIsLogin(Long.valueOf(user.get("id").toString()), tid);
            map.put("online", online);
            user.putAll(map);
        }
        Page page = (Page<Map<String, Object>>) userList;
        return new PageVO<>(page);
    }

    /**
     * 搜索条件
     *
     * @param queryUserDTO
     * @param query
     * @return
     */
    private Map<String, Object> initQueryParams(QueryUserDTO queryUserDTO, Map<String, Object> query) throws BizException {
		/*query.put("id", queryUserDTO.getId());
		query.put("name", queryUserDTO.getName());
		query.put("delFlag", EDeleteFlag.NORMAL.getKey());
		query.put("phone", queryUserDTO.getPhone());
		query.put("roleName",queryUserDTO.getRoleName());
		if (StringUtils.isNotEmpty(queryUserDTO.getIds())) {
		    query.put("ids", queryUserDTO.getIds().split(","));
		}
		query.put("realName", Optional.ofNullable(queryUserDTO.getRealName()).orElse(null));
		//默认拉取平台用户而非系统用户
		query.put("isSystem", Optional.ofNullable(queryUserDTO.getIsSystem()).orElse(0));
		if (queryUserDTO.getDeptId() != null && queryUserDTO.getDeptId() > 0) {
		    List<Long> listDept = deptService.getChildIds(queryUserDTO.getDeptId());
		    query.put("deptIds", listDept);
		}
		query.put("roleNum", 0);
		if (StringUtils.isNotEmpty(queryUserDTO.getRoleId())) {
		    String[] rids = queryUserDTO.getRoleId().split(",");
		    query.put("roleId", rids);
		    query.put("roleNum", rids.length);
		}
		//角色查询处理逻辑方式
		query.put("andOr", Optional.ofNullable(queryUserDTO.getAndOr()).orElse(null));*/
        return query;
    }

    /**
     * 用户信息查询
     *
     * @param queryUserDTO
     * @return
     */
    public PageVO<QueryUserVO> queryUserByPage(QueryUserDTO queryUserDTO) throws BizException {
        try {
			/*Map<String, Object> query = new HashMap<String, Object>(9);
			initQueryParams(queryUserDTO, query);
			Page<QueryUserVO> page = PageHelper.startPage(queryUserDTO.getPageNum(), queryUserDTO.getPageSize(), "id DESC");
			userDAO.listByFullUser(query);
			PageVO<QueryUserVO> pageVO = new PageVO<QueryUserVO>(page);
			List<QueryUserVO> list = page.getResult();
			list.forEach(row -> {
			    if (SysConstant.ADMIN_USER_NAME.equals(row.getName()) ||
			            SysConstant.SYSTEM_USER_NAME.equals(row.getName()) ||
			            row.getIsAdmin().equals(EYesOrNo.YES.getKey()) ||
			            row.getIsSystem().equals(EYesOrNo.YES.getKey())) {
			        row.setCanEdit(ECanEdit.NOT.getKey());
			    } else {
			        row.setCanEdit(ECanEdit.CAN.getKey());
			    }
			
			    Map<String, Object> map = new HashMap<String, Object>();
			    map.put("userId", row.getId());
			    row.setRoleIds(Convertor.converToRoleIds(userRoleDAO.listBy(map)));
			    if ("1".equals(row.getIsSystem().toString()) || row.getIsAdmin().equals(EYesOrNo.YES.getKey())) {
			//                if(row.getName().equals(SysConstant.ADMIN_USER_NAME) || row.getName().equals(SysConstant.SYSTEM_USER_NAME)){
			        row.setRoleName("内置角色");
			    }
			});
			pageVO.setData(list);*/
            return new PageVO<QueryUserVO>();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    /**
     * 根据主键查询用户
     *
     * @param userId
     * @return
     * @throws BizException
     */
    public QueryUserVO queryUserById(Long userId) throws BizException {
        try {
            UserPO userPO = userDAO.getById(userId);
            if (userPO == null) {
                return null;
            }
            QueryUserVO queryUserVO = new QueryUserVO();
            BeanUtils.copyProperties(userPO, queryUserVO);
            if (userPO.getDeptId() > 0) {
                DeptPO deptPO = deptDAO.getById(userPO.getDeptId());
                if (deptPO != null) {
                    queryUserVO.setDeptName(deptPO.getName());
                }
            }
            return queryUserVO;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    /**
     * 根据主键集合查询用户
     *
     * @param queryByIdsDTO
     * @return
     * @throws BizException
     */
    public List<QueryUserVO> queryUserByIds(QueryByIdsDTO queryByIdsDTO) throws BizException {
        try {
            List<UserPO> list = userDAO.queryUserByIds(queryByIdsDTO.getIds());
            List<QueryUserVO> reList = new ArrayList<>();
            list.forEach(row -> {
                QueryUserVO queryUserVO = new QueryUserVO();
                BeanUtils.copyProperties(row, queryUserVO);
                reList.add(queryUserVO);
            });
            return reList;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(AddUserDTO dto) throws Exception {
        UserPO po = userDAO.getByName(dto.getName());
        if (po != null) {
            throw new BizException("手机号已存在");
        }

        po = new UserPO();
        BeanUtils.copyProperties(dto, po);
        userDAO.insert(po);

        // 在运营端插入一条租户用户记录
		if (StringUtils.isBlank(aioFlag)) {// 云版本
		    tenantUserRemote.add(dto.getTenantId(), dto.getDataNode(), dto.getName());
		} else {// 一体机版本
	        try {
	        	Map<String, Object> tenantUserMap = Maps.newHashMap();
	        	tenantUserMap.put("tenantId", dto.getTenantId());
	        	tenantUserMap.put("userName", dto.getName());
	        	HttpClientHelper.sendPost(tenantUserAddUrl, JSON.toJSONString(tenantUserMap));
			} catch (Exception e) {
				logger.error("远程调用租户用户添加失败", e);
			}
		}

        if (StringUtils.isNotBlank(dto.getRoleIds())) {
            //给用户分配角色
            addUserRole(po.getId(), Convertor.converToInteger(dto.getRoleIds()));
        }
    }

    /**
     * 创建用户数据
     *
     * @param createUserDTO
     * @return
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public UserPO createUser(CreateUserDTO createUserDTO, Integer uId, String tid) throws BizException {
        try {
            UserPO oldUserPo = userDAO.getByName(createUserDTO.getName());
            if (null != oldUserPo) {
                throw new BizException("登录名已存在");
            }

            if (StringUtils.isNotEmpty(createUserDTO.getPhone())) {
                UserPO oldUser = userDAO.getByPhone(createUserDTO.getPhone());
                if (null != oldUser) {
                    throw new BizException("用户手机号已存在");
                }
            }
            //验证密码是否符合安全策略
            checkPassword(createUserDTO.getPrivateKey(), tid);
            Date nowTime = new Date();
            UserPO userPO = new UserPO();
            BeanUtils.copyProperties(createUserDTO, userPO);
            //userPO.setCreateBy(uId);
            //userPO.setCreateAt(nowTime);
            //userPO.setUpdateAt(nowTime);
            //userPO.setUpdateBy(uId);
            userPO.setIsSystem(Integer.parseInt(createUserDTO.getIsSystem().toString()));
            userPO.setIsAdmin(Integer.parseInt(createUserDTO.getIsAdmin().toString()));
            //userPO.setDelFlag(EDeleteFlag.NORMAL.getKey());

            // 获取用户所属公司id
			/*if (createUserDTO.getDeptId() != null && createUserDTO.getDeptId() > 0) {
			    DeptPO deptPO = deptService.getTopDept(createUserDTO.getDeptId());
			    if (deptPO == null) {
			        userPO.setCompanyId(0);
			    } else {
			        userPO.setCompanyId(Integer.valueOf(String.valueOf(deptPO.getId())));
			    }
			} else {
			    userPO.setCompanyId(0);
			    userPO.setDeptId(0L);
			}*/

            int num = userDAO.insert(userPO);
            if (num <= 0) {
                throw new BizException("创建用户失败");
            }
            //缓存用户
            //adminService.addRedisUser(userPO, tid);
            //noticeEventService.publishEvent(new NoticesEvent(this, EventEnum.USER, EventActionEnum.CREATE, String.valueOf(userPO.getId())));
			/*if (StringUtils.isNotBlank(createUserDTO.getRoleIds())) {
			    //给用户分配角色
			    addUserRole(userPO.getId(), Convertor.converToInteger(createUserDTO.getRoleIds()));
			}*/
            return userPO;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(ExceptionMessageFilter.filter(e.getMessage()));
        }
    }

    /**
     * 运营端远程创建超级管理员用户
     *
     * @param dto
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public void createAdminUser(CreateAdminUserDTO dto) throws BizException {
        UserPO po = userDAO.getByName(dto.getName());
        if (po != null) {
            throw new BizException("登录名已存在");
        }
        po = new UserPO();
        BeanUtils.copyProperties(dto, po);
        userDAO.insert(po);
    }

    /**
     * saas平台更新租户产品包信息
     *
     * @param dto
     * @return
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateApp(UpdateAppDTO dto) throws BizException {
        try {
            //授权应用
            platformService.enableApp(dto.getPrefixs());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(ExceptionMessageFilter.filter(e.getMessage()));
        }
    }

    /**
     * 添加用户角色
     *
     * @param userId
     * @param roleIds
     * @return
     * @throws BizException
     */
    public boolean addUserRole(Long userId, List<Integer> roleIds) throws BizException {
        UserRoleDTO userRoleDTO = new UserRoleDTO();
        userRoleDTO.setUserId(userId);
        userRoleDTO.setRoleIds(roleIds);
        return awardedRole(userRoleDTO);
    }

    /**
     * 更新用户数据
     *
     * @param dto
     * @return
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(UpdateUserDTO dto) throws BizException {
        // 新用户名和旧用户名不一致时对新用户名做校验
        if (!StringUtils.equals(dto.getName(), dto.getOldName())) {
            UserPO po = userDAO.getByName(dto.getName());
            if (po != null) {
                throw new BizException("手机号已存在");
            }
        }
        UserPO po = new UserPO();
        BeanUtils.copyProperties(dto, po);
        userDAO.update(po);

        //先删除用户之前的对应角色关系数据
        deleteUserRole(po.getId());
        if (StringUtils.isNotBlank(dto.getRoleIds())) {
            //给用户分配角色
            addUserRole(po.getId(), Convertor.converToInteger(dto.getRoleIds()));
        }
    }


    /**
     * 更新用户数据
     *
     * @param updateUserDTO
     * @return
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateBaseUser(UpdateBaseUserDTO updateUserDTO, Integer uId, String tid) throws BizException {
        try {
            UserPO userPO = userDAO.getById(updateUserDTO.getId());
            if (userPO == null) {
                throw new BizException("修改对象不存在或已被删除");
            }
            if (StringUtils.isNotBlank(updateUserDTO.getName())) {
                Map<String, Object> existMap = new HashMap<>(3);
                existMap.put("name", updateUserDTO.getName());
                existMap.put("id", updateUserDTO.getId());
                UserPO userExist = userDAO.userNameIsExist(existMap);
                if (userExist != null) {
                    throw new BizException("登录名已存在");
                }
            }
            if (StringUtils.isNotEmpty(updateUserDTO.getPhone())) {
                Map<String, Object> existPhoneMap = new HashMap<>(3);
                existPhoneMap.put("phone", updateUserDTO.getPhone());
                existPhoneMap.put("id", updateUserDTO.getId());
                List<UserPO> userPhoneExist = userDAO.userPhoneIsExist(existPhoneMap);
                if (CollectionUtils.isNotEmpty(userPhoneExist)) {
                    throw new BizException("用户手机号已存在");
                }
            }
            String oldPwd = userPO.getPwd();
            UserPO newUserPo = userPO;
            BeanUtils.copyProperties(updateUserDTO, newUserPo);
            //当密码为空时不更新密码
            if (null == updateUserDTO.getPwd() || updateUserDTO.getPwd().isEmpty()) {
                newUserPo.setPwd(userPO.getPwd());
                newUserPo.setPrivateKey(userPO.getPrivateKey());
            } else {
                if (updateUserDTO.getOldPasswd() == null || !oldPwd.equals(updateUserDTO.getOldPasswd())) {
                    throw new BizException("旧密码错误！");
                }
                //验证密码是否符合安全策略
                checkPassword(updateUserDTO.getPrivateKey(), tid);
                newUserPo.setPwd(updateUserDTO.getPwd());
                newUserPo.setLastChangePwd(new Date());
            }
            //newUserPo.setUpdateAt(new Date());
            //newUserPo.setUpdateBy(uId);

            int num = userDAO.update(newUserPo);
            if (num <= 0) {
                throw new BizException("更新用户失败");
            }
            //更新用户缓存
            adminService.addRedisUser(userDAO.getById(newUserPo.getId()), tid);
            noticeEventService.publishEvent(new NoticesEvent(this, EventEnum.USER, EventActionEnum.MODIDY, String.valueOf(newUserPo.getId())));
            //给用户分配角色
            return num;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(ExceptionMessageFilter.filter(e.getMessage()));
        }
    }

    /**
     * 启停用户
     *
     * @param updateUserStatusDTO
     * @param uId
     * @return
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateUserStatus(UpdateUserStatusDTO updateUserStatusDTO, Integer uId, String tid) throws BizException {
        try {
            UserPO userPO = userDAO.getById(updateUserStatusDTO.getId());
            if (userPO == null) {
                throw new BizException("修改对象不存在或已被删除");
            }
            if (SysConstant.ADMIN_USER_NAME.equals(userPO.getName()) ||
                    SysConstant.SYSTEM_USER_NAME.equals(userPO.getName()) ||
                    userPO.getIsAdmin().equals(EYesOrNo.YES.getKey()) ||
                    userPO.getIsSystem().equals(EYesOrNo.YES.getKey())) {
                throw new BizException("不能操作当前帐户");
            }
            UserPO newUserPo = new UserPO();
            newUserPo.setId(updateUserStatusDTO.getId());
            newUserPo.setStatus(updateUserStatusDTO.getStatus().shortValue());
            //newUserPo.setUpdateAt(new Date());
            //newUserPo.setUpdateBy(uId);
            int num = userDAO.update(newUserPo);
            if (num > 0) {
                userPO.setStatus(newUserPo.getStatus());
                adminService.addRedisUser(userPO, tid);
                noticeEventService.publishEvent(new NoticesEvent(this, EventEnum.USER, EventActionEnum.MODIDY, String.valueOf(newUserPo.getId())));
            }
            return num;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(ExceptionMessageFilter.filter(e.getMessage()));
        }
    }

    /**
     * 更新用户密码
     *
     * @param dto
     * @return
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public void updatePwd(UpdateUserPwdDTO dto) throws BizException {
        try {
            //当密码为空时不更新密码
            if (null == dto.getPwd() || dto.getPwd().isEmpty()) {
                throw new BizException("没有需要修改的密码");
            }
            //验证密码是否符合安全策略
            UserPO userPO = userDAO.getById(dto.getId());
            if (userPO == null) {
                throw new BizException("修改对象不存在或已被删除");
            }
            if (!StringUtils.equals(userPO.getPwd(), dto.getOldPwd())) {
                throw new BizException("旧密码不匹配");
            }
            userPO = new UserPO();
            userPO.setId(dto.getId());
            userPO.setPwd(dto.getPwd());
            userDAO.update(userPO);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(ExceptionMessageFilter.filter(e.getMessage()));
        }
    }

    /**
     * 更新用户关注数据卡片配置
     *
     * @param dto
     * @return
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFollowCards(UpdateFollowCardsDTO dto) throws BizException {
        try {
            UserPO userPO = userDAO.getById(dto.getId());
            userPO = new UserPO();
            userPO.setId(dto.getId());
            userPO.setFollowCards(dto.getFollowCards());
            userDAO.update(userPO);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(ExceptionMessageFilter.filter(e.getMessage()));
        }
    }

    /**
     * 根据登录账号修改密码，该接口用于运营端修改租户的时候调用
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    public void updatePwd(UpdateUserPwdRemoteDTO dto) {
        userDAO.updatePwdByName(dto.getPwd(), dto.getName());
    }

    /**
     * 删除用户（标记删除，非物理删除）
     *
     * @param idDTO
     * @return
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(DeleteBaseDTO dto) throws BizException {
        UserPO po = new UserPO();
        BeanUtils.copyProperties(dto, po);
        userDAO.update(po);
    }

    /**
     * 用户角色权限分配
     *
     * @param userRoleDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean awardedRole(UserRoleDTO userRoleDTO) throws BizException {
        try {
            //删除之前的数据
            deleteUserRole(userRoleDTO.getUserId());
            //生成用户角色数据
            List<UserRolePO> list = generateUserRole(userRoleDTO);
            //批量写入数据
            if (list != null && list.size() > 0) {
                int num = userRoleDAO.insertBatch(list);
                if (num > 0) {
                    return true;
                }
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("处理数据失败！");
        }
    }

    /**
     * 生成用户角色数据
     *
     * @param userRoleDTO
     * @return
     */
    private List<UserRolePO> generateUserRole(UserRoleDTO userRoleDTO) {
        List<Integer> roleIds = userRoleDTO.getRoleIds();
        List<UserRolePO> list = new ArrayList<UserRolePO>();
        UserRolePO userRolePO = null;
        if (roleIds == null || roleIds.size() == 0) {
            return list;
        }
        for (int roleId : roleIds) {
            userRolePO = new UserRolePO();
            userRolePO.setUserId(userRoleDTO.getUserId());
            userRolePO.setRoleId(roleId);
            list.add(userRolePO);
        }
        return list;
    }

    /**
     * 删除用户角色
     *
     * @param userId
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserRole(Long userId) throws BizException {
        try {
            userRoleDAO.deleteByUserId(userId);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("删除数据失败！");
        }
    }

    /**
     * 查询指定用户的所有角色数据
     *
     * @param queryUserRoleDTO
     * @return
     * @throws BizException
     */
    public List<QueryUserRoleVO> queryUserRoleAll(QueryUserRoleDTO queryUserRoleDTO) throws BizException {
        try {
            List<QueryUserRoleVO> list = userRoleDAO.listByUserId(queryUserRoleDTO.getUserId());
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    /**
     * 获取用户菜单
     *
     * @param queryUserResourceDTO
     * @return
     * @throws BizException
     */
    public List<QueryUserResourceVO> queryUserMenu(QueryUserResourceDTO queryUserResourceDTO, String tid) throws BizException {
        try {
//            queryUserResourceDTO.setType(EResourceType.MENU.getKey());
            return queryUserResource(queryUserResourceDTO, tid);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    /**
     * 根据条件获取用户资源数据
     *
     * @param queryUserResourceDTO
     * @return
     * @throws BizException
     */
    public List<QueryUserResourceVO> queryUserResource(QueryUserResourceDTO queryUserResourceDTO, String tid) throws BizException {
        try {
            //获取用户信息
            Map map = redisService.getMap(adminService.getUserRedisKey(queryUserResourceDTO.getUserId(), tid));
            if (map != null) {
                //如果用户是超级管理员（isAdmin=1）则返回指定平台的所有资源
                if ("1".equals(String.valueOf(map.get("isAdmin")))) {
                    return resourceService.queryByPrefix(queryUserResourceDTO.getPrefix());
                }
            }
            Map<String, Object> queryMap = new HashMap<>(5);
            queryMap.put("userId", queryUserResourceDTO.getUserId());
            queryMap.put("prefix", queryUserResourceDTO.getPrefix());
            queryMap.put("delFlag", EDeleteFlag.NORMAL.getKey());
            queryMap.put("useable", 0);
            return userDAO.listUserResource(queryMap);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    /**
     * 获取资源数据
     *
     * @param queryUserResourceDTO
     * @return
     * @throws BizException
     */
    public List<QueryUserResourceVO> queryResourceByIds(QueryUserResourceDTO queryUserResourceDTO, String tid) throws BizException {
        try {
//            if(StringUtils.isEmpty(queryUserResourceDTO.getResourceIds())){
//                return null;
//            }
            //获取用户信息
            Map map = redisService.getMap(adminService.getUserRedisKey(queryUserResourceDTO.getUserId(), tid));
            if (map != null) {
                //如果用户是超级管理员（isAdmin=1）则返回指定平台的所有资源
                if ("1".equals(String.valueOf(map.get("isAdmin")))) {
                    return resourceService.queryByPrefix(queryUserResourceDTO.getPrefix());
                }
            }
            Map<String, Object> queryMap = new HashMap<>(5);
            queryMap.put("userId", queryUserResourceDTO.getUserId());
            queryMap.put("prefix", queryUserResourceDTO.getPrefix());
            queryMap.put("delFlag", EDeleteFlag.NORMAL.getKey());
            if (StringUtils.isNotEmpty(queryUserResourceDTO.getResourceIds())) {
                queryMap.put("resourceIds", this.stringAryToLongAry(queryUserResourceDTO.getResourceIds().split(",")));
            }
            queryMap.put("useable", 0);
            return userDAO.listResourceByIds(queryMap);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }


    private List<Long> stringAryToLongAry(String[] ids) {
        if (ids != null && ids.length > 0) {
            List<Long> list = new ArrayList<>();
            for (String id : ids) {
                list.add(Long.valueOf(id));
            }
            return list;
        }
        return null;
    }

    public List<QueryUserResourceVO> listToTree(List<QueryUserResourceVO> list, Long pId) {
        List<QueryUserResourceVO> reList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (QueryUserResourceVO vo : list) {
                if (vo.getpId().equals(pId)) {
                    vo.setChildren(listToTree(list, vo.getId()));
                    reList.add(vo);
                }
            }
        }
        return reList;
    }

    /**
     * 根据条件获取用户所有资源数据
     *
     * @param queryUserResourceDTO
     * @return
     * @throws BizException
     */
    public List<QueryUserResourceVO> queryUserAllResource(QueryUserResourceDTO queryUserResourceDTO) throws BizException {
        try {
            Map<String, Object> queryMap = new HashMap<>(5);
            queryMap.put("userId", queryUserResourceDTO.getUserId());
            queryMap.put("delFlag", EDeleteFlag.NORMAL.getKey());
            queryMap.put("useable", 0);
            return userDAO.listUserResource(queryMap);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    /**
     * 获取用户所拥有的服务
     *
     * @param userId
     * @return
     * @throws BizException
     */
    public Map<String, Object> getUserResourceService(Integer userId) throws BizException {
        try {
            Map<String, Object> queryMap = new HashMap<>(7);
            queryMap.put("userId", userId);
            queryMap.put("type", EResourceType.MENU.getKey());
            queryMap.put("delFlag", EDeleteFlag.NORMAL.getKey());
            queryMap.put("pId", 0);
            queryMap.put("useable", 0);
            //用户拥有的服务
            List<QueryUserResourceVO> list = userDAO.listUserResource(queryMap);
            Set<String> prefixList = new HashSet<String>();
            list.forEach(row -> {
                prefixList.add(row.getPrefix());
            });
            //使用前5的服务
            List<QueryUserResourceVO> useTop5 = new ArrayList<>();
            if (prefixList.size() > 0) {
                Map<String, Object> map = new HashMap<>(4);
                map.put("userId", userId);
                map.put("list", prefixList);
                List<Map<String, Object>> top5Prefix = userServiceClickDAO.getServiceClickTop5(map);
                if (top5Prefix != null && top5Prefix.size() > 0) {
                    top5Prefix.forEach(item -> {
                        for (QueryUserResourceVO queryUserResourceVO : list) {
                            if (String.valueOf(item.get("prefix")).equals(queryUserResourceVO.getPrefix())) {
                                useTop5.add(queryUserResourceVO);
                                break;
                            }
                        }
                    });
                }
            }
            Map<String, Object> resMap = new HashMap<>(3);
            resMap.put("serviceList", list);
            resMap.put("useTop5", useTop5);
            return resMap;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    /**
     * 获取分组后用户服务
     *
     * @param userId
     * @return
     * @throws BizException
     */
    public Map<String, List<QueryUserResourceVO>> getGroupUserService(Integer userId, String tid) throws BizException {
        try {
            Map<String, Object> queryMap = new HashMap<>(7);
            UserPO userPO = getUserById(userId);
            if (userPO == null) {
                throw new BizException("登录用户信息异常！");
            } else {
                if (!userPO.getName().equals(SysConstant.ADMIN_USER_NAME)
                        && !userPO.getIsAdmin().equals(EYesOrNo.YES.getKey())) {
                    queryMap.put("userId", userId);
                }
            }
            queryMap.put("type", EResourceType.MENU.getKey());
            queryMap.put("delFlag", EDeleteFlag.NORMAL.getKey());
            queryMap.put("pId", 0);
            queryMap.put("useable", 0);
            //用户拥有的服务
            List<QueryUserResourceVO> list = userDAO.listUserResource(queryMap);
            //当设置需要强制修改密码时过滤掉其它菜单
            list = filterUserResource(userPO, list, tid);
            List<QueryUserResourceVO> newList = new ArrayList<>();
            list.forEach(row -> {
                row.setServiceGroup(Optional.ofNullable(row.getServiceGroup()).orElse("0"));
                switch (row.getServiceGroup()) {
                    case "1":
                        row.setServiceGroup(ServiceGroupFlagEnum.SMART_PRODUCTION.getDesc());
                        break;
                    case "2":
                        row.setServiceGroup(ServiceGroupFlagEnum.SMART_OPERATION.getDesc());
                        break;
                    case "3":
                        row.setServiceGroup(ServiceGroupFlagEnum.PLATFORM_MANAGEMENT.getDesc());
                        break;
                    default:
                        row.setServiceGroup(ServiceGroupFlagEnum.MANAGEMENT_COCKPIT.getDesc());
                        break;
                }
                newList.add(row);
            });
            return newList.stream().collect(Collectors.groupingBy(QueryUserResourceVO::getServiceGroup));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(ExceptionMessageFilter.filter(e.getMessage()));
        }
    }

    public List<QueryUserResourceVO> filterUserResource(UserPO userPO, List<QueryUserResourceVO> list, String tid) throws BizException {
        if ((StringUtils.isBlank(userPO.getLastLoginIp()) || userPO.getLastLoginTime() == null) && userPO.getLastChangePwd() == null) {
            Object obj = settingService.getSettingByKey(EUserSecurity.S_FIRST_LOGIN_CHANGE_PWD.getKey(), tid);
            if (Optional.ofNullable(obj).map(v -> Integer.valueOf(obj.toString())).orElse(0) > 0) {
                for (QueryUserResourceVO vo : list) {
                    if ("main.platform.info".equals(vo.getUrl())) {
                        List<QueryUserResourceVO> reList = new ArrayList<>();
                        reList.add(vo);
                        return reList;
                    }
                }
            }
        }
        return list;
    }

    /**
     * 根据用户名称查询对应的用户信息
     *
     * @param userName
     * @return
     */
    public UserPO getUserUsingUserName(String userName) throws BizException {
        try {
            UserPO users = userDAO.listByName(userName);
            return users;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取用户信息失败！");
        }
    }

    /**
     * 验证的用户名称和密码
     *
     * @param userInfo
     * @return
     */
    public UserPO verifyUser(Map<String, String> userInfo, String uniqueId) throws BizException {
        try {
            // (1)获取用户
            UserPO userPO = getUserUsingUserName(userInfo.get("userName").toString());
            if (userPO == null) {
                throw new BizException(EMessageKeyEnum.user_not_exist.getValue());
            }
			/*if (userPO.getDelFlag().equals(EDeleteFlag.DELETE.getKey())) {
			    throw new BizException(EMessageKeyEnum.user_not_exist.getValue());
			}
			if (userPO.getStatus() == 0) {
			    throw new BizException(EMessageKeyEnum.user_disable.getValue());
			}*/
            // 用户与登录平台不对应
//            if(!String.valueOf(userPO.getIsSystem()).equals(String.valueOf(userInfo.get("isSystem")))) {
//                throw new BizException(String.format("用户[%s]不允许登录该平台！",userPO.getName()));
//            }

            // (2)验证密码
            String userPasswordToBeVerified = userInfo.get("password").toString();
            if (userPO.getPwd() != null && userPO.getPwd().equals(userPasswordToBeVerified)) {
//                userPO.setPwd(null);
//                UserPO user = basicInfoService.findUserByIdFast(userPO.getId());
                validateUtils.isValidateCodeLogin(uniqueId, false, true);
                return userPO;
            } else {
                validateUtils.isValidateCodeLogin(uniqueId, true, false);
                throw new BizException(EMessageKeyEnum.user_not_exist.getValue());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(ExceptionMessageFilter.filter(e.getMessage()));
        }
    }

    /**
     * 获取用户角色和资源
     *
     * @param userId
     * @param prefix
     * @return
     * @throws BizException
     */
    public List<Map<String, Object>> getUserRoleResource(Long userId, String prefix) throws BizException {
        try {
            Map<String, Object> map = new HashMap<>(3);
            map.put("userId", userId);
            map.put("prefix", prefix);
            map.put("delFlag", EDeleteFlag.NORMAL.getKey());
            List<Map<String, Object>> list = userDAO.getUserRoleResource(map);
            if (list == null || list.size() == 0) {
                return null;
            }
            List<Map<String, Object>> reList = new ArrayList<>();
            Set<Integer> roleList = new HashSet<>();
            list.forEach(row -> {
                Integer roleId = Integer.valueOf(String.valueOf(row.get("role_id")));
                if (!roleList.contains(roleId)) {
                    Map<String, Object> thisMap = new HashMap<>(3);
                    thisMap.put("role_id", roleId);
                    thisMap.put("role_name", row.get("role_name"));
                    thisMap.put("resource", userRoleResourceAsTree(list, roleId, 0));
                    reList.add(thisMap);
                }
                roleList.add(roleId);
            });
            return reList;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    /**
     * 将列表数据转成树
     *
     * @param list
     * @param roleId
     * @param pID
     * @return
     */
    private List<Map<String, Object>> userRoleResourceAsTree(List<Map<String, Object>> list, Integer roleId, Integer pID) {
        List<Map<String, Object>> reList = new ArrayList<>();
        list.forEach(row -> {
            Integer role_id = Integer.valueOf(String.valueOf(row.get("role_id")));
            Integer pid = Integer.valueOf(String.valueOf(row.get("pid")));
            Integer id = Integer.valueOf(String.valueOf(row.get("id")));
            Map<String, Object> map = new HashMap<>(9);
            map.put("name", row.get("name"));
            map.put("nameen", row.get("nameen"));
            map.put("url", row.get("url"));
            if (role_id.equals(roleId) && pid.equals(pID)) {
                map.put("child", userRoleResourceAsTree(list, role_id, id));
                reList.add(map);
            }
        });
        return reList;
    }

    /**
     * 根据用户ID查询用户基础数据
     *
     * @param userId
     * @return
     * @throws BizException
     */
    public QueryUserVO queryUserByToken(Long userId) throws BizException {
        try {
            Map<String, Object> map = new HashMap<>(3);
            map.put("id", userId);
            List<QueryUserVO> list = userDAO.listByFullUser(map);
            if (list != null && list.size() > 0) {
                QueryUserVO queryUserVO = list.get(0);
                if ("1".equals(queryUserVO.getIsSystem().toString())) {
                    queryUserVO.setRoleName("内置角色");
                }
                return queryUserVO;
            } else {
                throw new BizException("没有相关数据");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(ExceptionMessageFilter.filter(e.getMessage()));
        }
    }

    /**
     * 检测用户是否安全
     *
     * @param userPO
     * @param ip
     * @param safeInfo
     * @return
     * @throws BizException
     */
    public boolean checkUserSecurity(UserPO userPO, String ip, Map<String, Object> safeInfo, String tid) throws BizException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        long now = calendar.getTimeInMillis();
        //第一次登陆是否需要修改密码
        if (StringUtils.isBlank(userPO.getLastLoginIp()) || userPO.getLastLoginTime() == null) {
            Object obj = settingService.getSettingByKey(EUserSecurity.S_FIRST_LOGIN_CHANGE_PWD.getKey(), tid);
            int isFirstChange = 0;
            if (null != obj) {
                isFirstChange = Integer.valueOf(obj.toString());
            }
            if (isFirstChange > 0 && userPO.getLastChangePwd() == null) {
                safeInfo.put("code", EUserSecurity.S_FIRST_LOGIN_CHANGE_PWD.getKey());
                safeInfo.put("msg", EUserSecurity.S_FIRST_LOGIN_CHANGE_PWD.getValue());
                return false;
            }
        } else {
            //更新用户登录信息
            updateUserLoginInfo(userPO, ip);
        }
        //检查是否长时间未修改密码
        if (userPO.getLastChangePwd() != null) {
            calendar.setTime(userPO.getLastChangePwd());
            long lastTime = calendar.getTimeInMillis();
            long diffTime = (now - lastTime) / (1000 * 24 * 3600);
            Object changePwdMaxDay = settingService.getSettingByKey(EUserSecurity.S_LONG_TIME_CHANGE_PWD.getKey(), tid);
            if (changePwdMaxDay == null || "".equals(changePwdMaxDay) || Integer.valueOf(changePwdMaxDay.toString()) == 0) {
                safeInfo.put("code", EUserSecurity.S_SAFE.getKey());
                safeInfo.put("msg", EUserSecurity.S_SAFE.getValue());
                return true;
            }
            long maxDay = Integer.valueOf(changePwdMaxDay.toString());
            if (diffTime > maxDay * 24 * 3600) {
                safeInfo.put("code", EUserSecurity.S_LONG_TIME_CHANGE_PWD.getKey());
                safeInfo.put("msg", EUserSecurity.S_LONG_TIME_CHANGE_PWD.getValue());
                return false;
            }
        }
        //非常用地登录提示
        if (StringUtils.isNotBlank(userPO.getLastLoginIp()) && !userPO.getLastLoginIp().equals(ip)) {
            safeInfo.put("code", EUserSecurity.S_UN_LOCAL_LOGIN.getKey());
            safeInfo.put("msg", EUserSecurity.S_UN_LOCAL_LOGIN.getValue());
        } else {
            safeInfo.put("code", EUserSecurity.S_SAFE.getKey());
            safeInfo.put("msg", EUserSecurity.S_SAFE.getValue());
        }
        return true;
    }

    /**
     * 用户登录信息更新
     *
     * @param userPO
     * @param ip
     */
    public void updateUserLoginInfo(UserPO userPO, String ip) {
        UserPO updateUser = new UserPO();
        updateUser.setId(userPO.getId());
        updateUser.setLastLoginIp(ip);
        updateUser.setLastLoginTime(new Date());
        //用户登录设备
        if (userPO != null) {
            updateUser.setLastLoginDevice(userPO.getLastLoginDevice());
        }
        userDAO.update(updateUser);
    }

    /**
     * 获取用户ID集
     *
     * @param name
     * @param id
     * @return
     * @throws BizException
     */
    public List<Map<String, Object>> getUserLikeCodeOrName(String name, Long id) throws BizException {
        try {
            return userDAO.getUserLikeCodeOrName(name, id);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    /**
     * 获取用户明文密钥
     *
     * @param id
     * @return
     * @throws BizException
     */
    public PrivateKeyVO getPrivateKey(Long id) throws BizException {
        try {
            return userDAO.getPrivateKey(id);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException("获取数据失败！");
        }
    }

    /**
     * 验证密码是否符合安全策略规则
     *
     * @param password
     */
    private void checkPassword(String password, String tid) throws BizException {
        if (password == null) {
            throw new BizException("密码不能为空");
        }
        //密码最小长度
        Object min = settingService.getSettingByKey(EUserSecurity.PASSWORD_MIN.getKey(), tid);
        if (min != null) {
            int len = Integer.parseInt(min.toString());
            if (password.length() < len) {
                throw new BizException(String.format("最小密码长度为：%d", len));
            }
        }
        //密码复杂度验证
        Object contain = settingService.getSettingByKey(EUserSecurity.PASSWORD_DIFFICULTY.getKey(), tid);
        if (contain != null && StringUtils.isNotEmpty(contain.toString())) {
            String strContain = contain.toString();
            String pattern;
            if (strContain.contains(EPasswordContain.NUMBER.getKey().toString())) {
                pattern = "\\d+";
                if (!Pattern.compile(pattern).matcher(password).find()) {
                    throw new BizException("密码必须包含数字");
                }
            }
            if (strContain.contains(EPasswordContain.ALPHABET.getKey().toString())) {
                pattern = "[a-zA-Z]+";
                if (!Pattern.compile(pattern).matcher(password).find()) {
                    throw new BizException("密码必须包含字母");
                }
            }
            if (strContain.contains(EPasswordContain.CHARS.getKey().toString())) {
                pattern = "([_+=?,./*&^%$#@!~`{}|;':\"<>]|-)+";
                if (!Pattern.compile(pattern).matcher(password).find()) {
                    throw new BizException("密码必须包含字符[_+=?,./*&^%$#@!~`{}|;':\"<>]");
                }
            }
        }
    }

    /**
     * 密码安全策略规则
     *
     * @return
     * @throws BizException
     */
    public Map<String, Object> passwordRule(String tid) throws BizException {
        Map<String, Object> map = new HashMap<>(4);
        Map keyMap = settingService.keyMap(tid);
        if (keyMap.containsKey(EUserSecurity.PASSWORD_MIN.getKey())) {
            map.put(EUserSecurity.PASSWORD_MIN.getKey(), keyMap.get(EUserSecurity.PASSWORD_MIN.getKey()));
        }
        if (keyMap.containsKey(EUserSecurity.PASSWORD_DIFFICULTY.getKey())) {
            map.put(EUserSecurity.PASSWORD_DIFFICULTY.getKey(), keyMap.get(EUserSecurity.PASSWORD_DIFFICULTY.getKey()));
        }
        return map;
    }

    /**
     * 将用户存入缓存
     */
    public void storageRedisUser(String tid) {
        adminService.storageRedisUser(userDAO.listBy(null), tid);
    }

    /**
     * 文档分类授权
     *
     * @return
     * @throws BizException
     */
    @Transactional(rollbackFor = Exception.class)
    public void authClassToUser(AuthClassToUserDTO dto, Integer userId, String tid) throws BizException {
        try {
            UserPO userPO = userDAO.getById(dto.getUserId());
            if (userPO == null) {
                throw new BizException("该用户不存在或已被删除");
            }
            UserPO newUserPo = new UserPO();
            newUserPo.setId(dto.getUserId());
            newUserPo.setClassIds(dto.getClassIds());
            //newUserPo.setUpdateAt(new Date());
            //newUserPo.setUpdateBy(userId);
            userDAO.update(newUserPo);
            // 更新用户缓存
            adminService.addRedisUser(userDAO.getById(dto.getUserId()), tid);

            LoggerUtil.sendOperatingRecord(Long.valueOf(userId), "文档分类授权", newUserPo.toString());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(e.getMessage());
        }
    }

    /**
     * 获取当前登录用户信息
     *
     * @param userId
     * @return
     */
    public QueryUserVO getCurrentUser(Long userId) throws BizException {
        try {
            QueryUserVO queryUserVO = new QueryUserVO();
			/*QueryUserDTO queryUserDTO = new QueryUserDTO();
			queryUserDTO.setId(userId);
			PageVO<QueryUserVO> pageVO = queryUserByPage(queryUserDTO);
			if (CollectionUtils.isNotEmpty(pageVO.getData())) {
			    queryUserVO = pageVO.getData().get(0);
			}*/
            return queryUserVO;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(e.getMessage());
        }
    }

    /**
     * 通过部门id查询人员或者负责人
     *
     * @return
     */
    public PageVO<UserPO> findUserByDeptId(ChairManUserDTO dto) {

        Map map = Maps.newHashMap();
        map.put("deptId", dto.getDeptId());
        map.put("status", 1);// 正常
        if (dto.getFlag()) {
            map.put("isAdmin", 1);// 是部门负责人的
        }
        Page<QueryUserVO> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize(),
                "id DESC");
        List<UserPO> list = userDAO.listBy(map);
        list.forEach(userPO -> {
            userPO.setPrivateKey("");
            userPO.setPwd(null);
        });
        return new PageVO<UserPO>(page);
    }

    public List<UserVO> list(QueryUserDTO dto) throws BizException {
        UserPO po = new UserPO();
        List<UserVO> list = userDAO.list(po);
        list.stream().forEach(p -> {
                    p.setPwd(null);
                    p.setRoleIds(Convertor.converToRoleIds(userRoleDAO.listBy(ImmutableMap.of("userId", p.getId()))));
                }
        );
        return list;
    }

    public List<UserOptionVO> optionList() {
        return userDAO.optionList();
    }

    /**
     * 查询指定机构部门及其子部门的所有用户列表
     *
     * @return
     * @throws BizException
     */
    public PageVO<UserPO> queryUsersListByDeptId(QueryUserByDeptIdDTO dto) throws BizException {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("deptIds", deptService.getChildIds(dto.getDeptId()));
            Page<UserPO> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize(), "id desc");
            List<UserPO> list = userDAO.queryUsersList(map);
            list.forEach(userPO -> {
                userPO.setPwd(null);
                userPO.setPrivateKey("");
            });
            return new PageVO<UserPO>(page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BizException(e.getMessage());
        }
    }

    /**
     * 根据ID获取用户信息
     *
     * @param userId
     * @return
     */
    public UserPO getUserById(Integer userId) {
        return userDAO.getById(userId.longValue());
    }

    /**
     * 获取用户的数据权限集合
     *
     * @param id
     * @return
     */
    public List<Integer> getUserDataResource(Integer id) {
        return userDAO.getUserDataResource(id);
    }

    /**
     * 获取指定部门的直属用户
     *
     * @param id
     * @return
     */
    public List<Long> queryUserByDeptId(Long id) {
        return userDAO.queryUserByDeptId(id);
    }

    public List<TenantUserVO> loginCheck(LoginCheckDTO dto) throws BizException {
        List<TenantUserVO> tenantUserVOS = userDAO.findByName(dto.getUserName());
        if (tenantUserVOS == null || tenantUserVOS.size() <= 0) {
            throw new BizException("登录账号校验失败");
        }
        return tenantUserVOS;
    }
}